package com.core.springSecurity.handle;

import com.common.utils.Constants;
import com.common.ErrorCodeEnum;
import com.common.utils.ServletUtils;
import com.common.utils.StringUtils;
import com.common.utils.Utils;
import com.core.asyncManager.AsyncManager;
import com.core.asyncManager.factory.AsyncFactory;
import com.core.springSecurity.model.LoginUserDetails;
import com.core.springSecurity.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 *
 *
 */
@Slf4j
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Resource
    private TokenService tokenService;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        LoginUserDetails loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getLoginKey());
            // 记录用户退出日志
            log.info("username:{},退出成功", userName);
           AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
        }
        ServletUtils.renderString(response, Utils.result(ErrorCodeEnum.SUCCESS).toJSONString());
    }
}
